package com.snu.liwei.lyl_api.config;

import com.snu.liwei.lyl_api.entity.User;
import com.snu.liwei.lyl_api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.snu.liwei.lyl_api.config.StaticConfig.SimRedis;

public class AuthHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("触发拦截器1");
        String access_token=request.getHeader("access_token");
        System.out.println("token:"+access_token );
        User user=new User();
        user.setToken(access_token);

        if (access_token!=null&&!access_token.equals(""))
        {
            if (findUserInCache(user))
            {
                System.out.println("从缓存取得，放行");
                return true;
            }
            else if (findUserInDb(user))
            {
                System.out.println("从db取得，放行");
                return true;
            }
            else {
                request.getRequestDispatcher("/hello/errInfo").forward(request,response);
                System.out.println("令牌验证失败拦截");
                return false;
            }
        }
        else
        {
            request.getRequestDispatcher("/hello/errInfo").forward(request,response);
            System.out.println("未登录拦截");
            return false;
        }
    }

    private boolean findUserInCache(User user) {
        boolean flag=SimRedis.containsKey(user.getToken());
        if (flag)
        {
            user=SimRedis.get(user.getToken());
            return true;
        }
        else
            return false;
    }

    private boolean findUserInDb(User user)
    {
        user=userService.getUser(user);
        if (user!=null)
            return true;
        else
            return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
